/**
 * @file 02_sum_sqr.c
 * @author your name (you@domain.com)
 * @brief 一个线程串行执行多个长时间的计算任务 vs 多个线程并行执行多个长时间的计算任务
 * @version 0.1
 * @date 2025-06-18
 * 
 * @copyright Copyright (c) 2025
 * 
 */
#include "unistd.h"
#include "sys/time.h"
#include "stdio.h"
#include "pthread.h"
#include "stdlib.h"

//一个需要一秒钟的计算任务函数
 int calu_sqr(int n) {
     sleep(1);
     return n * n;
 }

 void *sqr_thread_fun(void *arg) {
     int num = *(int *)arg;
     int *result = malloc(sizeof(int));
     *result = calu_sqr(num);

    // return result;
    pthread_exit(result);

 }

 int main(int argc, char const *argv[]) 
 {
     int items[5] = {1, 2, 3, 4, 5};
     int sqrs[5];
     struct timeval start, end;
     gettimeofday(&start, NULL);

     
    pthread_t pts[5];
     for (int i = 0; i < 5; i++)
     {
       pthread_create(&pts[i], NULL, sqr_thread_fun, &items[i]);
     }

     for (int i = 0; i < 5; i++)
     {
        void *result;
        pthread_join(pts[i], &result);
        sqrs[i] = *(int *)result;
     }
     
     gettimeofday(&end, NULL);
     printf("并行执行时间: %ld\n", end.tv_sec - start.tv_sec);

     //求和
     int sum = 0;
     for (int i = 0; i < 5; i++)
     {
        sum += sqrs[i];
     }
     printf("sum = %d\n", sum);

     return 0;
 }